package com.zsw.service.impl;

import com.zsw.dao.AccountDao;
import com.zsw.entity.Account;
import com.zsw.exception.BusinessException;
import com.zsw.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author zhangsw
 */
@Service
@Transactional(rollbackFor = {Exception.class})
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountDao accountDao;

    /**
     * 账户余额扣减
     * @param userId 用户编号
     * @param money 交易金额
     */
    @Override
    public boolean debit(Integer userId, BigDecimal money) {
        Account account = accountDao.getAccountByUserId(userId);
        if(account.getBalance().compareTo(money) < 0){
            throw new BusinessException("当前帐户余额不足");
        }
        BigDecimal val = account.getBalance().subtract(money);
        account.setBalance(val);
        int result=accountDao.updateAccount(account);
        return result > 0;
    }

    @Override
    public Account getAccountByUserId(Integer userId) {
        return accountDao.getAccountByUserId(userId);
    }
}
